﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Help;
using Model;
namespace BLLA
{
    public partial class Order_UserWalt_T : BaseBLL<Model.Order_UserWalt_T>, IBLL.IOrder_UserWalt_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();
        IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");


        #region 获取用户钱包
        /// <summary>
        /// 获取用户能够使用的钱包
        /// </summary>
        /// <param name="AccID">用户id</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string GetUserWalt(int AccID,  string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                List<Model.View_Order_UserWalt> ls = new List<Model.View_Order_UserWalt>();  //钱包信息
                ls = base.DBSession.IView_Order_UserWaltDAL.GetListBy("select * from View_Order_UserWalt where WaltState=1 and accid=" + AccID);
                string str_depID = base.DBSession.IView_UserDAL.GetListBy(u => u.AccID == AccID).First().DepID;

                #region 检查用户的钱包是否完整
                if (str_depID.Trim() != "")
                {
                    foreach (var item in ls)
                    {
                        
                        if (item.WaltDep != null)
                        {
                            #region MyRegion
                            string[] DepList = item.WaltDep.Split(',');

                            foreach (var DepId in DepList)
                            {
                                if (DepId.Length <= str_depID.Length)
                                {
                                    if (DepId == str_depID.Substring(0, DepId.Length))
                                    {
                                        List<Model.Order_UserWalt_T> Uw = base.DBSession.IOrder_UserWalt_TDAL.GetListBy(u => u.WaltID == item.WaltID & u.AccID == AccID);
                                        if (Uw.Count == 0)
                                        {
                                            Model.Order_UserWalt_T tm = new Model.Order_UserWalt_T();
                                            tm.AccID = AccID;
                                            tm.WaltID = item.WaltID;
                                            tm.WaltNowNub = 0;
                                            tm.LastUpTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                                            tm.BZ = "";
                                            tm.LastUpFlow = "";
                                            base.DBSession.IOrder_UserWalt_TDAL.Add(tm);
                                        }
                                    }
                                }
                            } 
                            #endregion
                        }
                    }
                }
                #endregion
                ls = base.DBSession.IView_Order_UserWaltDAL.GetListBy("select * from View_Order_UserWalt where WaltState=1 and accid=" + AccID);
                result.BS = "1";
                result.Msg = "查询成功";
                result.rows = ls;
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取个人钱包列表失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }
        #endregion
        #region 获取用户钱包信息
        /// <summary>
        /// 获取用户钱包信息
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <param name="AccName">用户姓名（""-全部）</param>
        /// <param name="AccCall">手机号（""-全部）</param>
        /// <param name="AccIdentifier">用户个人编号（""-全部）</param>
        /// <param name="AccCerNub">证件号（""-全部）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string GetOrder_UserWalt(int pageIndex, int pageSize, string AccName, string AccCall, string AccIdentifier, string AccCerNub, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 业务层
            List<Model.View_Order_UserWalt> mo = new List<Model.View_Order_UserWalt>();
            try
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("SELECT * FROM  View_Order_UserWalt where waltstate=1");
                if (AccName != "")
                {
                    sql.Append(" and AccName like'%" + AccName + "%'");
                }
                if (AccCall != "")
                {
                    sql.Append(" and AccCall like'%" + AccCall + "%'");
                }
                if (AccIdentifier != "")
                {
                    sql.Append(" and AccIdentifier like'%" + AccIdentifier + "%'");
                }
                if (AccCerNub != "")
                {
                    sql.Append(" and AccCerNub like'%" + AccCerNub + "%'");
                }

                mo = base.DBSession.IView_Order_UserWaltDAL.GetListBy(sql.ToString());
                List<int> acclist = (from m in mo select m.AccID).ToList();
                acclist = acclist.Distinct<int>().ToList();
                Order_Walt_T ow = new Order_Walt_T();
                foreach (var item in acclist)
                {
                    ow.CheckWalt(item);
                }
                mo = base.DBSession.IView_Order_UserWaltDAL.GetListBy(sql.ToString());
            }
            catch (Exception)
            {
                result.BS = "-1";
                result.Msg = "查询不到用户！";
                return os.StringOfObject(result, RETID);
            }
            result.BS = "1";
            result.Msg = "查询成功！";
            result.rows = mo.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            result.total = mo.Count;

            return os.StringOfObject(result, RETID);
            #endregion
        }
        #endregion

        #region 更新用户钱包信息
        /// <summary>
        /// 更新用户钱包信息
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="UserWaltID">用户钱包ID</param>
        /// <param name="updateMoney">金额</param>
        /// <param name="BZ">备注</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetOrder_UserWalt(int OperID, int UserWaltID, int Tag, string OrderID, int updateMoney, string BZ, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                List<Model.Order_UserWalt_T> list_info = base.GetListBy(u => u.UserWaltID == UserWaltID);
                if (list_info == null || list_info.Count <= 0)
                {
                    WriteLog.WriteW("更新用户钱包时，根据钱包ID查找钱包信息失败（积分ID：" + UserWaltID + "）");
                    result.BS = "0";
                    result.Msg = "更新失败";
                    return os.StringOfObject(result, RETID);
                }
                Model.Order_UserWalt_T info = list_info.First();
                Model.Order_UserWalt_T old_info = new Model.Order_UserWalt_T() { AccID = info.AccID, WaltID = info.WaltID, UserWaltID = info.UserWaltID, LastUpFlow = info.LastUpFlow, LastUpTime = info.LastUpTime, WaltNowNub = info.WaltNowNub, BZ = info.BZ };
                string T = "";
                int ret = -1;
                string time = new PublicMethod().getDateTimeNow();
                // 根据操作标签Tag判断是什么操作
                switch (2)
                {
                    case 1:
                        T = "新增";
                        break;
                    case 2:
                        T = "修改";
                        //Model.Order_UserWalt_T tmp = base.GetListBy(u => u.UserWaltID  == info.UserWaltID).First();
                        //Help.FuZhi<Model.Order_UserWalt_T>.FZ(ref tmp, info);
                        Model.Order_Walt_T ow = base.DBSession.IOrder_Walt_TDAL.GetListBy(u => u.WaltID == info.WaltID).First();
                        if ((info.WaltNowNub + updateMoney) > int.Parse(ow.WaltMax))
                        {
                            result.BS = "-2";
                            result.Msg = "充值不允许超过上限";
                            return os.StringOfObject(result, RETID);
                        }
                        //应用范围权限判断
                        if (updateMoney > 0)//充值
                        {
                            if (ow.WaltUsing.Substring(0, 1) == "0")
                            {
                                result.BS = "-2";
                                result.Msg = "该钱包没有权限充值";
                                return os.StringOfObject(result, RETID);
                            }

                        }
                        if (updateMoney < 0)//提现
                        {
                            if (ow.WaltUsing.Substring(2, 1) == "0")
                            {
                                result.BS = "-2";
                                result.Msg = "该钱包没有权限提现";
                                return os.StringOfObject(result, RETID);
                            }
                            else if ((updateMoney + old_info.WaltNowNub) < 0)
                            {
                                result.BS = "-2";
                                result.Msg = "该钱包冲正额度不能大于钱包余额";
                                return os.StringOfObject(result, RETID);
                            }
                        }

                        info.LastUpTime = time;
                        info.WaltNowNub += updateMoney;
                        ret = base.Modify(info);
                        break;
                    default:
                        T = "删除";
                        break;
                }

                if (ret > 0)
                {
                    #region 将操作记录到日志表中
                    Model.Order_OperationFlow_T Log = new Model.Order_OperationFlow_T();
                    Log.OperationTitle = "更改用户钱包信息";
                    Log.OperationText = T + "用户钱包信息成功";
                    Log.OperationType = "1F0006";
                    Log.OperationRes = "成功";
                    Log.OperationUser = OperID;
                    string str_log = os.StringOfObject(Log, RETID);
                    bool isSuccess = new Order_OperationFlow_T().AddOrder_OperationFlow(str_log, RETID);
                    if (!isSuccess)
                    {
                        WriteLog.WriteW("新增系统操作流水失败");
                    }
                    #endregion

                    #region 添加金额流水
                    Model.Order_FlowMon_T flowMon = new Model.Order_FlowMon_T();
                    flowMon.AccID = info.AccID;
                    flowMon.FlowMonID = GetSysKey.GetKey("FlowMonKey");
                    switch (Tag)
                    {
                        case 0:
                            flowMon.WaltFlowType = "1A0001";
                            break;
                        case 1:
                            flowMon.WaltFlowType = "1A0008";
                            break;
                        case 2:
                            flowMon.WaltFlowType = "1A0005";
                            break;
                    }
                    flowMon.WaltID = old_info.WaltID;
                    flowMon.WaltNowNub = old_info.WaltNowNub;
                    flowMon.WaltHaveNub = updateMoney;
                    flowMon.WaltEndNub = info.WaltNowNub;
                    flowMon.WaltFlowTime = time;
                    flowMon.WaltFlowOper = OperID;
                    if (OrderID != "")
                    {
                        flowMon.OrdrID = int.Parse(OrderID);
                    }
                    flowMon.WaltBZ = BZ;

                    int flowMon_res = bl.IOrder_FlowMon_TBLL.Add(flowMon);
                    if (flowMon_res <= 0)
                    {
                        WriteLog.WriteW("更新用户钱包时，新增金额流水失败");
                    }
                    #endregion

                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新钱包信息失败：" + ex.Message);
                result.BS = "-1";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
        #endregion

        #region MyRegion
        public List<Model.Order_UserWalt_T> GetOrder_UserWalt(int AccID, string WaltID)
        {
            List<Model.Order_UserWalt_T> UWList = new List<Model.Order_UserWalt_T>();
            try
            {
                UWList = base.GetListBy(u => u.AccID == AccID & u.WaltID == WaltID);
                if (UWList.Count != 0)
                {
                    string str_depID = base.DBSession.IView_UserDAL.GetListBy(u => u.AccID == AccID).First().DepID;
                    if (str_depID.Trim() == "")
                    {
                        result.BS = "-6";
                        result.Msg = "用户没有使用此钱包的权限";
                        return null;
                    }

                    Model.Order_Walt_T orderWalt = new Model.Order_Walt_T();
                    orderWalt = base.DBSession.IOrder_Walt_TDAL.GetListBy(u => u.WaltID == WaltID).First();
                    string[] DepList = orderWalt.WaltDep.Split(',');
                    bool jg = true;
                    foreach (var item in DepList)
                    {
                        if (item == str_depID.Substring(0, item.Length))
                        {
                            jg = false;
                            break;
                        }
                    }
                    if (jg)
                    {
                        result.BS = "-7";
                        result.Msg = "用户没有使用此钱包的权限";
                        return null;
                    }
                }

            }
            catch (Exception)
            {

            }

            return UWList;
        }
        #endregion
    }
}
